package com.test30_IO流;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * InputStream，字节输入流
 */
public class Demo02_InputStream {

    /**
     * 文件读取
     */
    @Test
    public void test1() {
        File file = new File("F:" + File.separator + "muyan" + File.separator + "vip" + File.separator + "yootk.txt");
        if (file.exists()) {
            try (InputStream input = new FileInputStream(file)) {   // 自动关闭流
                byte[] data = new byte[1024];
                int len = input.read(data);
                System.out.println("读取的数据内容【" + new String(data, 0, len) + "】");
            } catch (Exception e) {
            }
        }
    }

    /**
     * 执行数据的多次读取
     */
    @Test
    public void test2() {
        StringBuffer buffer = new StringBuffer();   // 保存读取到的内容
        File file = new File("F:" + File.separator + "muyan" + File.separator + "vip" + File.separator + "yootk.txt");
        if (file.exists()) {
            try (InputStream input = new FileInputStream(file)) {
                byte[] data = new byte[8];
                int len = 0;
                do {
                    len = input.read(data);
                    if (len != -1) {
                        buffer.append(new String(data, 0, len));
                    }
                } while (len != -1);
                System.out.println("读取的数据内容【" + buffer + "】");
            } catch (Exception e) {
            }
        }
    }

    /**
     * 通过while循环读取数据
     */
    @Test
    public void test3() throws Exception {
        StringBuffer buffer = new StringBuffer();   // 保存读取到的内容
        File file = new File("F:" + File.separator + "muyan" + File.separator + "vip" + File.separator + "yootk.txt");
        if (file.exists()) {
            try (InputStream input = new FileInputStream(file)) {
                byte[] data = new byte[8];
                int len = 0;
                while ((len = input.read(data)) != -1) {
                    buffer.append(new String(data, 0, len));
                }
                System.out.println("读取的数据内容【" + buffer + "】");
            } catch (Exception e) {
            }
        }
    }
}
